import request from "@/libs/request";
import store from "@/store";

const scope = "server";

export const loginByUsername = (username, password) => {
  const grant_type = "password";

  return request({
    url: "/webAuth/oauth/token",
    header: {
      isToken: false,
      Authorization: "Basic dGVzdDp0ZXN0",
    },
    method: "post",
    params: { username, password, grant_type, scope },
  });
};

export const refreshToken = (refresh_token) => {
  const grant_type = "refresh_token";
  return request({
    url: "/webAuth/oauth/token",
    header: {
      isToken: false,
      Authorization: "Basic dGVzdDp0ZXN0",
    },
    method: "post",
    params: { refresh_token, grant_type, scope },
  });
};

export const getUserInfo = () => {
  return request({
    url: "/student/webUser/info",
    method: "post",
  });
};

export const register = (data) => {
  return request({
    url: "/student/webUser/register",
    method: "post",
    data,
  });
};

export const logout = () => {
  return request({
    url: "/webAuth/token/logout",
    method: "delete",
  });
};

/**
 * 校验令牌，若有效期小于半小时自动续期
 * @param refreshLock
 */
export const checkToken = (refreshLock, $store) => {
  const token = store.getters.access_token;

  request({
    url: "/webAuth/oauth/check_token",
    header: {
      isToken: false,
      Authorization: "Basic dGVzdDp0ZXN0",
    },
    method: "get",
    params: { token },
  })
    .then((response) => {
      const expire = response && response.exp;
      if (expire) {
        const expiredPeriod = expire * 1000 - new Date().getTime();
        console.log("当前token过期时间", expiredPeriod, "毫秒");
        //小于半小时自动续约
        if (expiredPeriod <= 30 * 60 * 1000) {
          if (!refreshLock) {
            refreshLock = true;
            $store.dispatch("RefreshToken").catch(() => {
              clearInterval(this.refreshTime);
            });
            refreshLock = false;
          }
        }
      }
    })
    .catch((error) => {
      console.error(error);
    });
};
